/*
*业绩统计 
*/
import React from 'react';
import { Breadcrumb, Button, Input, Cascader, Icon, Table, Modal, message, DatePicker } from 'antd';
import $ from 'jquery';
import moment from 'moment';
import Config from '../../../common/config';
import './achievement.less';

const config = new Config();
const token = sessionStorage.getItem('token');
const RangePicker = DatePicker.RangePicker;
const InputGroup = Input.Group;

class Achievement extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            name: '',
            sort: { //排序状态 false降序 true升序
                orderMoney: false,
                collectionMoney: false,
                depositMoney: false,
                signMoney: false,
                unsignDeposit: false,
                refundMoney: false,
                wayMoney: false,
                orderTotal: false,
                signCount: false,
                achievements: false
            },
            dates: [moment().startOf('day'), moment().startOf('day').add(1, 'day')],
        }
    }
    //生命周期函数 加载前
    componentWillMount() {
        this.getdata();
    }
    //生命周期函数 加载完成后
    componentDidMount() {

    }
    //获取统计分析数据
    getdata(obj) {
        let data = {};
        if (obj) {
            data = obj;
        }
        $.ajax({
            type: 'get',
            url: config.CrmStatistics + '/achievementsStatistics',
            data: data,
            headers: { Authorization: 'Bearer ' + token },
            success: res => {
                console.log(res);
                const tree = this.buildtree(res.data);
                console.log(tree);
                this.setState({ list: tree })
            }
        })
    }
    //生成统计树
    buildtree(arr) {
        return arr.map(item => {
            console.log('item', item)
            item.key = item.name + item.id
            item.achievements = 0
            item.collectionMoney = 0
            item.depositMoney = 0
            item.newUser = 0
            item.oldUser = 0
            item.orderCount = 0
            item.orderMoney = 0
            item.refundMoney = 0
            item.signCount = 0
            item.signMoney = 0
            item.unsignDeposit = 0
            item.wayMoney = 0
            if (item.son.length || item.userData.length) {
                item.children = [];
                item.son.forEach(son => {
                    son.key = son.name + son.id
                    son.achievements = 0
                    son.collectionMoney = 0
                    son.depositMoney = 0
                    son.newUser = 0
                    son.oldUser = 0
                    son.orderCount = 0
                    son.orderMoney = 0
                    son.refundMoney = 0
                    son.signCount = 0
                    son.signMoney = 0
                    son.unsignDeposit = 0
                    son.wayMoney = 0
                    if (son.userData.length) {
                        son.userData.forEach(user => {
                            son.achievements += user.achievements
                            son.collectionMoney += user.collectionMoney
                            son.depositMoney += user.depositMoney
                            son.newUser += user.newUser
                            son.oldUser += user.oldUser
                            son.orderCount += user.orderCount
                            son.orderMoney += user.orderMoney
                            son.refundMoney += user.refundMoney
                            son.signCount += user.signCount
                            son.signMoney += user.signMoney
                            son.unsignDeposit += user.unsignDeposit
                            son.wayMoney += user.wayMoney
                        })
                    }
                    item.achievements += son.achievements
                    item.collectionMoney += son.collectionMoney
                    item.depositMoney += son.depositMoney
                    item.newUser += son.newUser
                    item.oldUser += son.oldUser
                    item.orderCount += son.orderCount
                    item.orderMoney += son.orderMoney
                    item.refundMoney += son.refundMoney
                    item.signCount += son.signCount
                    item.signMoney += son.signMoney
                    item.unsignDeposit += son.unsignDeposit
                    item.wayMoney += son.wayMoney
                    item.children.push(son);
                    if (son.son.length || son.userData.length) {
                        son.children = [];
                        son.children.push(...this.buildtree(son.son))
                        son.userData = son.userData.map((item, i) => {
                            item.key = son.user[i];
                            return item;
                        })
                        son.children.push(...son.userData);
                    }
                    console.log(son);
                })
            }
            return item;
        })
    }
    //树结构 遍历排序
    loopdata(arr, columns) {
        //console.log('columns', columns);
        const dep = arr.filter(item => item.department);
        const emp = arr.filter(item => item.username);
        emp.sort((a, b) => { console.log(a[columns]); return a[columns] - b[columns] });
        const tree = [...emp, ...dep];
        return tree.map(item => {
            if (item.children) {
                item.children = this.loopdata(item.children, columns);
            }
            return item;
        })
    }
    sortTree(bool, key, list) { //bool：true升序 false降序，key：排序的键，list:排序树
        const dep = [], user = [];
        list.forEach(item => {
            if (item.name) {
                dep.push(item);
            }
            if (item.username) {
                user.push(item);
            }
            if (item.children && item.children.length) {
                item.children = this.sortTree(bool, key, item.children);
            }
        })
        user.sort((a, b) => a[key] - b[key]);
        return [...user, ...dep]
    }
    tableSort(key) {
        const { sort, list } = this.state;
        console.log(key, list, sort);
        sort[key] = !sort[key];
        const sortlist = this.sortTree(sort[key], key, list);
        console.log(sortlist)
        this.setState({
            sort,
            list:sortlist
        })
    }
    //获取搜索时间
    getDate(dates, dateStrings) {
        console.log(dates, dateStrings);
        this.setState({ dates })
    }
    //重置搜索
    resetSearch() {
        this.setState({
            name: '',
            dates: [moment().startOf('day'), moment().startOf('day').add(1, 'day')]
        })
    }
    //搜索
    searchData() {
        const { name, dates } = this.state;
        console.log(name, dates, new Date(dates[0]).getTime());
        const data = {
            userName: name,
            startDate: new Date(dates[0]).getTime(),
            endDate: new Date(dates[1]).getTime() - 1,
        }
        this.getdata(data);
    }
    //表格行选择
    rowSelection() {
        return {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(selectedRowKeys, selectedRows);
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                console.log(selected, selectedRows, changeRows);
            },
        }
    };
    render() {
        const columns = [
            { title: '部门', width: 200, fixed: 'left', dataIndex: 'name', key: 'name' },
            { title: '姓名', width: 100, fixed: 'left', dataIndex: 'username', key: 'username' },
            { title: <div className='sorter' onClick={() => { this.tableSort('orderMoney') }}><span>下单金额</span><Icon type={this.state.sort.orderMoney ? 'caret-up' : 'caret-down'} /></div>, width: 100, dataIndex: 'orderMoney', key: 'orderMoney', },
            { title: <div className='sorter' onClick={() => { this.tableSort('collectionMoney') }}><span>代收金额</span><Icon type={this.state.sort.collectionMoney ? 'caret-up' : 'caret-down'} /></div>, width: 100, dataIndex: 'collectionMoney', key: 'collectionMoney', },
            { title: <div className='sorter' onClick={() => { this.tableSort('depositMoney') }}><span>订金金额</span><Icon type={this.state.sort.depositMoney ? 'caret-up' : 'caret-down'} /></div>, width: 100, dataIndex: 'depositMoney', key: 'depositMoney', },
            { title: <div className='sorter' onClick={() => { this.tableSort('signMoney') }}><span>已签收金额</span><Icon type={this.state.sort.signMoney ? 'caret-up' : 'caret-down'} /></div>, width: 120, dataIndex: 'signMoney', key: 'signMoney', },
            { title: <div className='sorter' onClick={() => { this.tableSort('unsignDeposit') }}><span>未签收订金</span><Icon type={this.state.sort.unsignDeposit ? 'caret-up' : 'caret-down'} /></div>, width: 120, dataIndex: 'unsignDeposit', key: 'unsignDeposit', },
            { title: <div className='sorter' onClick={() => { this.tableSort('refundMoney') }}><span>退款金额</span><Icon type={this.state.sort.refundMoney ? 'caret-up' : 'caret-down'} /></div>, width: 100, dataIndex: 'refundMoney', key: 'refundMoney', },
            { title: <div className='sorter' onClick={() => { this.tableSort('wayMone') }}><span>在途金额</span><Icon type={this.state.sort.wayMone ? 'caret-up' : 'caret-down'} /></div>, width: 100, dataIndex: 'wayMoney', key: 'wayMoney', },
            {
                title: <div className='sorter' onClick={() => { this.tableSort('orderTotal') }}><span>订单总数量(新+老)</span><Icon type={this.state.sort.orderTotal ? 'caret-up' : 'caret-down'} /></div>, width: 160, dataIndex: 'orderTotal', key: 'orderTotal', render: (text, record) => (
                    <div>
                        <span>{record.oldUser + record.newUser}</span>
                        <span>{`(${record.oldUser}+${record.newUser})`}</span>
                    </div>
                )
            },
            { title: <div className='sorter' onClick={() => { this.tableSort('signCount') }}><span>签收订单数</span><Icon type={this.state.sort.signCount ? 'caret-up' : 'caret-down'} /></div>, width: 120, dataIndex: 'signCount', key: 'signCount' },
            { title: <div className='sorter' onClick={() => { this.tableSort('achievements') }}><span>最终业绩金额</span><Icon type={this.state.sort.achievements ? 'caret-up' : 'caret-down'} /></div>, width: 120, dataIndex: 'achievements', key: 'achievements' },
        ]
        return (
            <div className='contentBox clearfix'>
                <div className='breadcrumb'>
                    <Breadcrumb separator='>'>
                        <Breadcrumb.Item>直销管理</Breadcrumb.Item>
                        <Breadcrumb.Item>统计分析</Breadcrumb.Item>
                        <Breadcrumb.Item>业绩统计</Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <div style={{ overflow: 'hidden' }}>
                    <div className='member-content-Search clearfix'>
                        <div className='addetd addetd-a addetd-kk addr-yo'>
                            <InputGroup compact>
                                <span className='chengge-a fkov-a' style={{ width: 100 }}>开始/结束时间:</span>
                                <div className='chengge-d' style={{ marginRight: 0 }}>
                                    <RangePicker
                                        ranges={{
                                            '今天': [moment().startOf('day'), moment().endOf('day')],
                                            '本周': [moment().startOf('week'), moment().endOf('week')],
                                            '本月': [moment().startOf('month'), moment().endOf('month')],
                                            '本年': [moment().startOf('year'), moment().endOf('year')],
                                        }}
                                        //disabledTime={this.disabledRangeTime.bind(this)}
                                        showTime={{ hideDisabledOptions: true, format: 'HH:mm' }}
                                        value={this.state.dates}
                                        allowClear
                                        onChange={this.getDate.bind(this)}
                                        format="YYYY-MM-DD HH:mm"
                                    />
                                </div>
                            </InputGroup>
                        </div>
                        <div className='addetd addetd-b indtner shuerwq-1'>
                            <Input className='addetd-a-r' addonBefore="员工" placeholder="请输入" value={this.state.name} onChange={(e) => { this.setState({ name: e.target.value }) }} />
                        </div>
                        <Button type='primary' className='member-button-aa' onClick={() => { this.searchData() }}>搜索</Button>
                        <Button type='primary' className='member-button-aa' onClick={() => { this.resetSearch() }}>重置</Button>
                    </div>
                </div>
                <Table
                    bordered
                    defaultExpandAllRows
                    columns={columns}
                    rowSelection={this.rowSelection()}
                    dataSource={this.state.list}
                    pagination={false}
                    className='totalTable'
                    scroll={{ x: 1500, y: 800 }}
                />
            </div>
        )
    }
}

export default Achievement;